package com.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.chat.entry.dto.message.MessageDTO;
import com.chat.entry.enums.MessageType;
import com.chat.entry.po.User;
import com.chat.entry.po.UserMessage;
import com.chat.entry.vo.message.MessageListVo;
import com.chat.entry.vo.message.UserMessageVO;
import com.chat.mapper.UserMessageMapper;
import com.chat.result.Result;
import com.chat.service.IUserMessageService;
import com.chat.websocket.ChatMessageHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户聊天表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-21
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements IUserMessageService {
    private final ChatMessageHandler chatMessageHandler;
    private final UserMessageMapper userMessageMapper;

    @Override
    public Result sendMessage(MessageDTO messageDTO) {
        // 1️⃣ 将数字类型转为枚举
        MessageType messageType = MessageType.fromValue(messageDTO.getType());

        if (messageType == null) {
            return Result.error("无效的消息类型");
        }

        switch (messageType) {
            case TEXT:
                UserMessage userMessage = new UserMessage();
                BeanUtils.copyProperties(messageDTO, userMessage);
                userMessage.setType(MessageType.TEXT);
                userMessage.setReadStatus(0);
                userMessage.setSendTime(LocalDateTime.now());

                boolean save = save(userMessage);
                if (!save) {
                    return Result.error("消息发送失败");
                }

                boolean send = chatMessageHandler.sendTextContent(userMessage);
                if (send) {
                    return Result.success("消息发送成功", null);
                } else {
                    return Result.success("对方不在线", null);
                }
            case EMOJI:
                break;
            case IMAGE:
                break;
            case VIDEO:
                break;
        }
        return Result.error("还未开发出来");
    }

    @Override
    public Result getUnreadSummary(Integer receiverId) {
        // 好有未读消息
        List<UserMessageVO.FriendUnread> friendUnreadList = userMessageMapper.selectMaps(
                new QueryWrapper<UserMessage>()
                        .select("sender_id as senderId, COUNT(*) as unreadCount")
                        .eq("receiver_id", receiverId)
                        .eq("read_status", 0)
                        .groupBy("sender_id")
        ).stream().map(map -> new UserMessageVO.FriendUnread(
                (Integer) map.get("senderId"),
                ((Long) map.get("unreadCount")).intValue()
        )).collect(Collectors.toList());

        log.info("friendUnreadList:{}", friendUnreadList);

        // 总未读消息数量
        int totalUnread = friendUnreadList.stream().mapToInt(
                UserMessageVO.FriendUnread::getUnreadCount).sum();

        return Result.success("查询成功", new UserMessageVO(totalUnread, friendUnreadList, null));
    }

    @Override
    public Result getMessageList(Integer userId) {
        List<UserMessage> userMessages = userMessageMapper.selectLastMessages(userId);

        List<MessageListVo> messageList = userMessages.stream().map(msg -> {
            MessageListVo vo = new MessageListVo();

            vo.setMessageId(msg.getId());

            // 确定对方 id
            Integer contactId = msg.getSenderId().equals(userId) ? msg.getReceiverId() : msg.getSenderId();
            vo.setUserId(contactId);

            // 消息类型
            vo.setMessageType(msg.getType());

            // 内容
            vo.setLastContent(msg.getContent());

            // 查询对方用户信息
            User user = Db.lambdaQuery(User.class)
                    .eq(User::getUid, contactId)
                    .one();
            if (user != null) {
                vo.setName(user.getNickname());
                vo.setAvatar(user.getAvator());
            }

            return vo;
        }).collect(Collectors.toList());

        return Result.success("查询成功", messageList);
    }

    @Override
    public Result queryMessage(Integer userId, Integer friendId, Integer pageNum, Integer pageSize) {
        Page<UserMessage> page = new Page<>(pageNum, pageSize);

        Page<UserMessage> result = userMessageMapper.selectPage(
                page,
                new LambdaQueryWrapper<UserMessage>()
                        .and(wrapper -> wrapper
                                .eq(UserMessage::getSenderId, userId)
                                .eq(UserMessage::getReceiverId, friendId)
                        )
                        .or(wrapper -> wrapper
                                .eq(UserMessage::getSenderId, friendId)
                                .eq(UserMessage::getReceiverId, userId)
                        )
                        .orderByDesc(UserMessage::getSendTime)
        );

        return Result.success("查询成功", result);
    }

    @Override
    public Result queryMessageByContent(Integer userId, Integer friendId, Long messageId, Integer pageSize) {
        // 1️⃣ 找到第一条匹配的消息
        UserMessage target = userMessageMapper.selectOne(
                new LambdaQueryWrapper<UserMessage>()
                        .eq(UserMessage::getId, messageId)
        );

        if (target == null) {
            return Result.error("未找到相关聊天记录");
        }

        // 2️⃣ 计算它在第几页
        Long countBefore = userMessageMapper.selectCount(
                new LambdaQueryWrapper<UserMessage>()
                        .and(w -> w.eq(UserMessage::getSenderId, userId)
                                .eq(UserMessage::getReceiverId, friendId))
                        .or(w -> w.eq(UserMessage::getSenderId, friendId)
                                .eq(UserMessage::getReceiverId, userId))
                        .lt(UserMessage::getSendTime, target.getSendTime())
        );

        int pageNum = (int) (countBefore / pageSize) + 1;

        // 3️⃣ 查出该页数据
        Page<UserMessage> page = new Page<>(pageNum, pageSize);
        Page<UserMessage> result = userMessageMapper.selectPage(
                page,
                new LambdaQueryWrapper<UserMessage>()
                        .and(w -> w.eq(UserMessage::getSenderId, userId)
                                .eq(UserMessage::getReceiverId, friendId))
                        .or(w -> w.eq(UserMessage::getSenderId, friendId)
                                .eq(UserMessage::getReceiverId, userId))
                        .orderByAsc(UserMessage::getSendTime)
        );

        Map<String, Object> data = new HashMap<>();
        data.put("pageNum", pageNum);
        data.put("pageSize", pageSize);
        data.put("records", result.getRecords());
        data.put("targetId", target.getId());

        return Result.success("查询成功", data);
    }


    @Override
    public Result searchMessage(Integer userId, String content) {
        List<UserMessage> userMessages = userMessageMapper.selectList(
                new LambdaQueryWrapper<UserMessage>()
                        .like(UserMessage::getContent, content)
        );

        List<MessageListVo> messageList = userMessages.stream().map(msg -> {
            MessageListVo vo = new MessageListVo();

            vo.setMessageId(msg.getId());

            // 确定对方 id
            Integer contactId = msg.getSenderId().equals(userId) ? msg.getReceiverId() : msg.getSenderId();
            vo.setUserId(contactId);

            // 消息类型
            vo.setMessageType(msg.getType());

            // 内容
            vo.setLastContent(msg.getContent());

            // 查询对方用户信息
            User user = Db.lambdaQuery(User.class)
                    .eq(User::getUid, contactId)
                    .one();
            if (user != null) {
                vo.setName(user.getNickname());
                vo.setAvatar(user.getAvator());
            }

            return vo;
        }).collect(Collectors.toList());

        if (!userMessages.isEmpty()) {
            return Result.success("查询成功", messageList);
        } else {
            return Result.error("没有聊天记录");
        }
    }
}
